<template>
    <a-modal
      :title="(mdl.id ? '编辑':'新增')+'角色'"
      :width="800"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading">
        <a-form :form="form" v-bind="formLayout">
          <a-form-item label="ID" style="display: none;">
            <a-input v-decorator="['id']" />
          </a-form-item>
          <a-form-item label="角色名称">
            <a-input placeholder="请输入角色名称" v-decorator="['name', { rules: [{ required: true, message: '请输入角色名称' }] }]" />
          </a-form-item>
          <a-form-item label="角色描述">
            <a-input placeholder="请输入角色描述" v-decorator="['description', { rules: [{ required: true, message: '请输入角色描述' }] }]" />
          </a-form-item>
          <a-form-item label="状态">
            <a-radio-group v-decorator="['status', { rules: [{ required: true, message: '请选择状态' }] }]">
              <a-radio :value="1">正常</a-radio>
              <a-radio :value="0">禁用</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="菜单权限">
            <a-tree-select
              style="width: 100%"
              :tree-data="permissions"
              tree-checkable
              :show-checked-strategy="SHOW_CHILD"
              search-placeholder="请选择权限"
              v-decorator="['permissions', { rules: [{validator: validPermissions}] }]"
            />
          </a-form-item>
          <a-form-item label="数据权限">
            <a-select v-decorator="['dataScope', { rules: [{ required: true, message: '请选择数据权限' }] }]" placeholder="请选择数据权限" @change="handleChangeScope">
              <a-select-option :value="1">所有</a-select-option>
              <a-select-option :value="2">自定义部门</a-select-option>
              <a-select-option :value="3">本部门及以下部门</a-select-option>
              <a-select-option :value="4">本部门</a-select-option>
              <a-select-option :value="5">自己</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="人员权限">
            <a-radio-group v-decorator="['userScope', { rules: [{ required: true, message: '请选择人员权限' }] }]" :default-value="0">
              <a-radio :value="0">同数据权限</a-radio>
              <a-radio :value="1">全员</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-spin>
  
    </a-modal>
  </template>
  
  <script>
  import { TreeSelect } from 'ant-design-vue'
  import { permissionTree } from '@/api/role'
  import { getTreeApi } from '@/api/role'
  import pick from 'lodash.pick'
  const SHOW_CHILD = TreeSelect.SHOW_CHILD
  const fields = ['id', 'name', 'description', 'status', 'permissions', 'dataScope', 'depts', 'userScope']
  
  export default {
    name: 'RoleModal',
    data () {
      return {
        visible: false,
        formLayout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 4 }
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 12 }
          }
        },
        form: this.$form.createForm(this),
        mdl: {},
        permissions: [],
        confirmLoading: false,
        SHOW_CHILD,
        deptTree: []
      }
    },
    created () {
      this.loadPermissions()
      // 防止表单未注册
      fields.forEach(v => this.form.getFieldDecorator(v))
      // 当 model 发生改变时，为表单设置值
      this.$watch('mdl', () => {
        if (this.mdl) {
          this.form.setFieldsValue(pick(this.mdl, fields))
        }
      })
      this.getDeptTree()
    },
    methods: {
      loadPermissions () {
        const that = this
        permissionTree().then(res => {
          const result = res.data
          // console.log(result)
          if (result.length) { that.permissions = that.deepTree(result, '') }
          console.log('that.permissions')
          console.log(that.permissions)
        })
      },
      deepTree (list, parentPerms) {
        return list.map(permission => {
          const obj = {}
          obj.title = permission.title
          obj.key = permission.id
          obj.value = permission.id
          obj.parent = parentPerms
          if (permission.children && permission.children.length) { obj.children = this.deepTree(permission.children, permission.id) }
          return obj
        })
      },
      // handleSelect (checkedKeys, e, extra) {
      //   console.log('handleSelect', extra.allCheckedNodes, extra.allCheckedNodes[0].node.data.props)
      //   let arr = []
      //   extra.allCheckedNodes.forEach(item => {
      //     arr = [...arr, item.node.data.props.value, item.node.data.props.parent]
      //   })
      //   arr = [...new Set(arr)]
      //   arr = arr.filter(v => !!v)
      //   console.log('arr === ', arr)
      //   this.mdl.permissions = arr
      // },
      validPermissions (rule, value, callback) {
        console.log('validPermissions', value)
        if (!value || value.length === 0) { callback('请选择权限') }
        callback()
      },
      handleChangeScope (e) {
        console.log(e)
        this.mdl.dataScope = e
      },
      getDeptTree () {
        getTreeApi({}).then(res => {
          this.deptTree = this.deepDeptTree(res.data, '')
        })
      },
      deepDeptTree (data, parentId) {
        return data.map(item => {
          const obj = {
            title: item.label,
            key: item.id,
            value: item.id,
            parent: parentId
          }
          if (item.children && item.children.length) {
            obj.children = this.deepDeptTree(item.children, item.id)
          }
          return obj
        })
      },
      validDepts (rule, value, callback) {
        console.log('validDepts', value)
        if (!value || value.length === 0) { callback('请选择部门') }
        callback()
      },
      handleOk () {
        const permissions = this.form.getFieldValue('permissions')
        const parentIds = []
        // 获取父级id
        for (let i = 0;i<this.permissions[0].children.length; i++) {
          const itemi = this.permissions[0].children[i]
          console.log(i)
          if (permissions.includes(itemi.value)) continue
          for (let j=0;j<itemi.children.length;j++) {
            console.log(j)
            const itemj = itemi.children[j]
            if (permissions.includes(itemj.value)) {
              if (!parentIds.includes(itemi.value)) parentIds.push(itemi.value)
            }
          }
        }
        this.mdl.permissions = [this.permissions[0].value].concat(permissions, parentIds)
        this.$emit('ok')
      },
      handleCancel () {
        this.visible = false
        this.form.resetFields()
      }
    }
  }
  </script>
  
  <style scoped>
  
  </style>
  